<!--
 * @Descripttion: 材料出库分单弹窗
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-06-09 15:10:06
 * @LastEditors: GW
 * @LastEditTime: 2022-06-09 13:42:19
-->

<template>
    <div class="content-wrapper a-base-container">
        <a-modal :visible="purchaseInVisible" @cancel="purchaseClose" :title="'生成材料出库单'" wrapClassName="separate-bill-wrapper" width="80%">
            <div style="position:relative;bottom:-5px;">材料未出库明细表</div>
            <a-table class="search-table-list shend-wrapper" :columns="searchCloums" :scroll="{x:500,y:100}" :data-source="searchBackData" :customRow="customClick" :rowClassName="rowClassName" bordered :pagination="pagination">
                <slot slot="businessType" slot-scope="text,record">
                    {{handleBusinessType(record)}}
                </slot>
            </a-table>

            <div class="requisition-set-wrapper" v-show="editOrderBox">
                <!-- 按钮 -->
                <!-- <div class="btn-wrapper clearfix">
                    <a-row class="text-center clearfix">
                        <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                            <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                <div class="btns" @click="submitServer">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                        </a-col>
                    </a-row>
                </div> -->
                <div ref="print" class="documents-wrapper" id="documents-wrapper">
                    <!-- <h3 class="text-center">
                        成品入库分单
                    </h3> -->
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                        </div>
                        <div class="table-box">
                            <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClickOrder" :scroll="{ x: 1000, y: 260 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <!-- <template slot="realBaseQuantity" slot-scope="text, record,">
                                    <div>
                                        {{record.baseQuantity}}
                                    </div>
                                </template> -->
                                <template v-if="isRouterAlive" slot="number" slot-scope="text, record, index">

                                    <div v-if="index == dataSource.length-1">
                                        合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in ['warehouseName','baseQuantity','sourceVoucherType']" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                        </div>
                    </a-form-model>
                    <div class="edit-mask" v-show="editMask">
                        <!-- 遮罩（点击修改关闭遮罩） -->
                    </div>
                </div>
                <div class="contextmenu-box">
                    <!-- 右键菜单 -->
                    <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                        <!-- <li @click="handleAdd()">新增行</li> -->
                        <li @click="handleDelete()">删除行</li>
                        <!-- <li @click="handleCopy()">复制行</li> -->
                    </ul>
                </div>
                <!-- <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox> -->
            </div>
            <template slot="footer">
                <div v-show="editOrderBox">
                    <a-button type="primary" @click="submitServer">确认</a-button>
                    <a-button @click="purchaseClose" class="margin-left-10">取消</a-button>
                </div>
            </template>
        </a-modal>
    </div>
</template>
<script>

import { purchaseSave, examine, purchaseDelete, getCode } from '@/api/inventory/inout'
import { IdFieldToNameField } from "@/utils/customize"
import { list as listDesign } from "@/api/erp/voucherDesign"; //动态表单数据
import { list as listSearch } from '@/api/purchase/voucherDesign';//搜索列表
import MiddleUtils from '@/utils/middle-utils';
import { deepCopy } from "@/utils/tool/object";
import pro from '@/mixins/procurement/pro'

export default {
    mixins: [pro],
    data () {
        return {
            purchaseInVisible: false,
            sourceCode: 'MaterialDispatchVoucher',
            receiveDeliverType: 1,//1入，2出

            searchArray: [],        //搜索条件
            searchCloums: [],
            searchCloumsDetails: [],  //明细cloums
            searchBackData: [],

            dynamicFormDataPop: [],//单据动态字段

            pagination: {
                size: "small",
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                position: 'top'
            },
            customClick: (record, index) => ({
                on: {
                    click: (event) => {
                        event.preventDefault();
                        this.mouseIndex = index;
                        this.editOrderBox = true;
                         //深拷贝
                        record= deepCopy(record, true);
                        this.editClickOrder(record, 'iscreate')
                    }
                },
            }),
            customClickOrder: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        if (record.number != "合计") {
                            this.openMenu(e);
                            console.log('右键点击的', index);
                            this.thisClickId = index;
                            this.thisClickRecord = record;
                        }
                    },
                    click: () => {
                        // console.log(record);
                    }
                },
            }),

            editOrderBox: false,
            mouseIndex: null,//当前选中的表格数据
            isFenDanType: null,
            dragModalLoc: null,



            headerInWherehouse: true,//弹框 隐藏表头的仓库字段 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
            headerInBusinessType: true,//弹框 表头业务类型不可修改 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
        };
    },
    created () {
        //this.getIdByData();//获取最新一条数据

        //隐藏仓库
        // console.log('表头表头表头：',this.orderHeaderData);
        // this.orderHeaderData.forEach(element => {
        //     if (element.code == 'warehouseId') {
        //         element.onOff = false;
        //         element.onEdit = true;
        //     }
        // });
    },
    methods: {
        //新增
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },
        //保存
        submit (requestData) {
            purchaseSave(requestData).then(response => {
                this.isSaveRun = true;
                if (response.code === 200) {
                    this.$message.success('生单成功');



                    // this.searchList(1, 2, 4);
                    // this.editOrderBox = false;
                    this.purchaseClose();
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            purchaseDelete(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            let data = {
                sourceCode: this.sourceCode
            }
            getCode(data).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        purchaseShowModel (type) {
            this.isFenDanType = type;//分单类型（1.完工单入库，2.退货单入库）
            let isrealnum = this.columns.some(item => item.dataIndex == 'realBaseQuantity');

            if (!isrealnum) {
                let realInNumCloum = {
                    title: '应入库数量',
                    key: 'realBaseQuantity',
                    dataIndex: 'realBaseQuantity',
                    // scopedSlots: { customRender: 'realBaseQuantity' },
                    width: 140,
                    ellipsis: true,
                }
                let indexQuantity = this.columns.map(item => item.key).indexOf('baseQuantity')
                this.columns.splice(indexQuantity, 0, realInNumCloum);


                this.columns.forEach(element => {
                    if (element.dataIndex == 'baseQuantity') {
                        element.title = <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 实际入库数量</div>
                    }
                });
            }


            console.log(this.dataSource)

            this.purchaseInVisible = true;

            //生产完工
            this.handleDynamicData();

            this.$nextTick(() => {
                let dragModalBox = document.getElementsByClassName('ant-modal-content')[0];
                dragModalBox.style.transform = 'none';
                this.dragModalLoc = dragModalBox.getBoundingClientRect();
            })

        },
        purchaseClose () {
            this.purchaseInVisible = false;
            this.editOrderBox = false;
            MiddleUtils.$emit('getIdByData');
        },










        //获取动态字段
        handleDynamicData () {
            let data = {
                source: 'RRS'
            }
            listDesign(data).then((response) => {
                if (response.code === 200) {
                    const { data } = response;
                    this.dynamicFormDataPop = data;

                    if (this.dynamicFormDataPop) {
                        this.handleSearchCloum();
                    }

                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //处理搜索数据
        handleSearchArray () {
            const { dynamicFormDataPop } = this;
            let data = [];
            for (let i = 0; i < dynamicFormDataPop.length; i++) {
                if ((dynamicFormDataPop[i].dataTab == '表头' || dynamicFormDataPop[i].dataTab == '表尾') && dynamicFormDataPop[i].isSearch && dynamicFormDataPop[i].columnType == '文本') {
                    data.push(dynamicFormDataPop[i]);
                }
            }
            if (data.length > 0) {
                this.searchArray = Object.assign([], data);
            } else {
                this.$message.error('没有可以搜索的条件');
            }


        },
        //动态searchCloums组装
        handleSearchCloum () {
            const { dynamicFormDataPop } = this;
            let searchCloums = [];

            let dynamicFormAllData = dynamicFormDataPop.filter(item => {
                return (item.dataTab == '表头' || item.dataTab == '表尾') && item.onOff == true;
            });

            dynamicFormAllData.forEach(element => {
                let code = element.code;
                if (element.columnType == '搜索选择') {
                    code = IdFieldToNameField(element.code)
                }

                let item = {
                    title: element.name,
                    key: code,
                    dataIndex: code,
                    width: 130,
                    ellipsis: true,
                }
                if (element.code == 'businessType') {
                    //业务类型
                    this.$set(item, 'scopedSlots', { customRender: 'businessType' });
                }
                if (element.code == 'sourceVoucherType') {
                    //业务类型
                    this.$set(item, 'scopedSlots', { customRender: 'sourceVoucherType' });
                }
                searchCloums.push(item)
            });
            Object.assign(this.searchCloums, searchCloums);
            //到货单->入库单
            if (this.isFenDanType == 1) {

                this.searchList(1, 2, 2);
            }
            //退货单->入库单
            if (this.isFenDanType == 2) {
                this.searchList(1, 1, 4);
            }
        },

        searchList (voucherState, businessType, searchType) {
            //选单的列表
            const { dynamicFormDataPop, searchArray } = this;
            let data = {
                designSearchDtos: [],
                page: {
                    current: this.pagination.current,
                    size: this.pagination.pageSize,
                },
                // voucherState: voucherState,
                // businessType: businessType,
                searchType: searchType, //"查询类型 
            }

            data.designSearchDtos = dynamicFormDataPop

            listSearch(data).then((response) => {
                if (response.code === 200) {
                    let backdData = response.data.records;
                    console.log('--------搜索返回值：', backdData);

                    this.getCode();

                    backdData.forEach(record => {

                        //删除制单日期，审核日期，变更日期
                        // record.updateDate = null;
                        // record.createDate = null;
                        // record.reviewerDate = null;
                        
                        //选单
                        this.$set(record, 'sourceVoucherId', record.id);    //来源id
                        this.$set(record, 'sourceVoucherCode', record.voucherCode);    //来源单号
                        this.$set(record, 'sourceVoucherDate', record.voucherDate);    //来源日期
                        // this.$set(record, 'sourceVoucherType', this.sourceCode);   //来源单据
                        this.$set(record, 'sourceVoucherType', 'RRS');   //来源单据

                        //选单明细 来源置入
                        for (let i = 0; i < record.detailList.length; i++) {
                            // record.detailList[i].sourceVoucherId = record.detailList[i].id;
                            record.detailList[i].sourceVoucherId = record.id;
                            record.detailList[i].sourceVoucherCode = record.voucherCode;    //来源单号
                            record.detailList[i].sourceVoucherDate = record.voucherDate;    //来源日期
                            record.detailList[i].sourceVoucherType = record.sourceVoucherType;    //来源单据

                            

                            record.detailList[i].baseQuantity = Math.abs(record.detailList[i].baseQuantity) - (record.detailList[i].cumExecuteQuantity ? record.detailList[i].cumExecuteQuantity : 0);
                            record.detailList[i].orgBaseQuantity = record.detailList[i].baseQuantity;
                            record.detailList[i].realBaseQuantity = record.detailList[i].baseQuantity.toFixed(2);
                        }
                       
                    });
                    backdData.forEach(element => {
                        element.detailList = element.detailList.filter(item => item.baseQuantity != 0);
                    })
                    console.log('--------处理后的值', backdData);

                    this.searchBackData = backdData;
                    this.mouseIndex = null;


                    //模拟点击第一条数据
                    if (backdData.length > 0) {
                        this.mouseIndex = 0;
                        this.editOrderBox = true;
                         //深拷贝
                        let record= deepCopy(backdData[0], true);
                        this.editClickOrder(record, 'iscreate')
                    }

                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        handleBusinessType (record) {
            let back = '';
            this.dynamicFormDataPop.forEach(item => {
                //处理业务类型的展示
                let val = [];
                if (item.code == 'businessType') {
                    val = JSON.parse(item.val);

                    let a = val.filter(c => { return c.key == record.businessType });
                    if (a.length > 0) {
                        back = a[0].label;
                    }
                }
            });
            return back;
        },
        rowClassName (record, index) {
            return this.mouseIndex == index ? 'hoverRowStyl' : '';
        },
        //=============================== 右键（新增，删除，修改） ==========================
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - this.dragModalLoc.left;
            var y = e.pageY - this.dragModalLoc.top;
            this.top = y;
            this.left = x;
            this.visible = true;
        },

    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .shend-wrapper {
        margin-top: -40px;
    }
    .shend-wrapper .hoverRowStyl {
        background-color: rgba(24, 144, 255, 0.2);
    }
    .search-table-list tr td {
        cursor: pointer;
    }
    .separate-bill-wrapper {
        .ant-modal {
            top: 0 !important;
        }
        .ant-modal-body {
            padding-top: 5px;
        }
    }
</style>